<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel</title>

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
    <script type="text/javascript" src="js/app.js"></script>

    <!-- Styles -->
    <style>
        html, body {
            background-color: #fff;
            color: #636b6f;
            font-family: 'Nunito', sans-serif;
            font-weight: 200;
            height: 100vh;
            margin: 0;
        }

        .full-height {
            height: 100vh;
        }

        .flex-center {
            display: flex;
            justify-content: center;
        }

        .position-ref {
            position: relative;
        }

        .room {
            width: 420px;
            height: 600px;
            border: #4e555b 1px solid;
            overflow-y: scroll;
        }

        .content {
            text-align: center;
        }

        .title {
            font-size: 42px;
        }

        .links > a {
            color: #636b6f;
            padding: 0 25px;
            font-size: 13px;
            font-weight: 600;
            letter-spacing: .1rem;
            text-decoration: none;
            text-transform: uppercase;
        }

        .m-b-md {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<div class="flex-center position-ref full-height">

    <div class="content">
        <div class="title m-b-md">
            websocket chat
        </div>

        <div class="room">
        </div>
        <div class="input-group" style="margin-top:10px;">
            <input type="text" height="160px" id="input-message" placeholder="your message"
                   style="float: left;width: 60%;line-height: 30px">
            <input type="number" height="160px" id="to" placeholder="to"
                   style="float: left;width: 10%;line-height: 30px">
            <button type="submit" id="btn" style="float: right;width: 50px;line-height: 30px">发送</button>
        </div>

    </div>
</div>
</body>
<script>

    $("#btn").click(function (event) {
        var message = $('#input-message').val();
        var to = $('#to').val();
        console.log('to:' + to);
        console.log("send message :" + message);
        SendData(message, to);
    });

    var url = 'ws://127.0.0.1:9502';
    var ws;
    var lockReconnect = false; //避免ws重复连接

    createWebSocket(url);//连接服务器

    function createWebSocket(url) {
        try {
            if ('WebSocket' in window) {
                console.log("连接 WebSocket");
                ws = new WebSocket(url);
            } else if ('MozWebSocket' in window) {
                console.log("尝试重新连接 MozWebSocket");
                ws = new MozWebSocket(url);
            } else {
                alert("您的浏览器不支持websocket")
            }
            ws.onopen = function (event) {
                heartCheck.start(); //心跳检测重置
                console.log("已经与服务器建立了连接\r\n当前连接状态：" + this.readyState);
            };

            ws.onmessage = function (event) {
                heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的
                if (event.data !== 'ping') {
                    buildReceiveMessage(event.data);
                    console.log("接收到服务器发送的数据：\r\n" + event.data);
                }
            };
            ws.onclose = function (event) {
                console.log("已经与服务器断开连接\r\n当前连接状态：" + this.readyState);
                reconnect(url);
            };
            ws.onerror = function (event) {
                console.log("WebSocket异常！");
                reconnect(url);
            };
        } catch (e) {
            reconnect(url);
            console.log(e);
        }

    }


    function reconnect(url) {
        if (lockReconnect) return;
        lockReconnect = true;
        setTimeout(function () { //没连接上会一直重连，设置延迟避免请求过多
            console.log("尝试重新连接");
            createWebSocket(url);//连接服务器
            lockReconnect = false;
        }, 2000);
    }


    function isJSON(str) {
        if (typeof str == 'string') {
            try {
                let obj = JSON.parse(str);
                if (typeof obj == 'object') {
                    return true;
                } else {
                    return false;
                }
            } catch (e) {
                return false;
            }
        }
    }

    function SendData(message, to) {
        try {
            if (message) {
                console.log("发送数据:" + message);
                var param = {};
                param.msg = message;
                param.to = to;
                ws.send(JSON.stringify(param));
                buildSendMessage(message);
            }

        } catch (ex) {
            alert(ex.message);
        }
    }

    function buildReceiveMessage(message) {
        message = JSON.parse(message);
        $('.room').append("<div style='width: 100%;text-align: left;'><div style='font-size: xx-small;margin-right: 5px;padding-left: 5px'>" + message.from + "</div><div style='display:inline-block ;border: #4e555b 1px solid;background-color: #d6e9f8;text-align: left;color: #1d2124;font-weight: bold;margin: 0 5px 10px 5px;border-radius: 8px;padding: 2px 5px'>" + message.msg + "</div></div>");
    }

    function buildSendMessage(message) {
        $('.room').append("<div style='width: 100%;text-align: right;'><div style='font-size: xx-small;margin-right: 5px;padding-right: 5px'>我</div><div style='display:inline-block ;border: #4e555b 1px solid;background-color: #2a9055;text-align: right;color: #1d2124;font-weight: bold;margin: 0 5px 10px 5px;border-radius: 8px;padding: 2px 5px'>" + message + "</div></div>");
    }

    //心跳检测
    var heartCheck = {
        timeout: 15000, //15s
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function () {
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
        },
        start: function () {
            var self = this;
            this.timeoutObj = setTimeout(function () {
                //这里发送一个心跳，后端收到后，返回一个心跳消息，
                //onmessage拿到返回的心跳就说明连接正常
                ws.send("ping");
                console.log("ping!");
                self.serverTimeoutObj = setTimeout(function () { //如果超过一定时间还没重置，说明后端主动断开了
                    console.log("try=close");
                    ws.close();
                }, self.timeout)
            }, this.timeout)
        }
    };
</script>
</html>
